﻿using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

namespace SimpleORM
{
    public class LeftJoinTranslator : LambdaTranslator
    {
        #region Properties


        #endregion

        #region Ctor

        public LeftJoinTranslator()
        {
        }

        #endregion

        #region Methods

        #region Methods - Public

        public void Translate(Expression selectMany, LambdaExpression where)
        {
            MethodCallExpression m = selectMany as MethodCallExpression;

            LambdaExpression join = ((m.Arguments[1] as UnaryExpression).Operand as LambdaExpression);
            IQueryable qc = join.Compile().DynamicInvoke(new object[] { null }) as IQueryable;

            ExpressionTranslater t = DataSource.CreateExpressionTranslater();
            t.Translate(qc.Expression);

            ObjectContextDictionary.Set(t.ResultObjectContext);

            Stack.Push(t.Result.
                  Bracket().
                  As(DataSource.CreateScriptFactory().
                  Constant(FromNameDictionary.Set(t.ResultObjectContext.ElementType)).
                  Stress()));

            this.Visit(Evaluator.PartialEval(where));

            List<IScriptFactory> list = Stack.ToList();
            list.Reverse();

            IScriptFactory target = list[0];
            IScriptFactory on = list[1];

            Result = DataSource.CreateScriptFactory().JoinLeft(target, on);

            //SelectTranslator = new SelectTranslator();
            //SelectTranslator.Factory = Factory;
            //SelectTranslator.ObjectContextDictionary = ObjectContextDictionary;
            //SelectTranslator.FromNameDictionary = FromNameDictionary;
            //SelectTranslator.Translate((expression.Arguments[4] as UnaryExpression).Operand as LambdaExpression);
        }

        #endregion

        #region Methods - Visit

        //protected override Expression VisitConstant(ConstantExpression c)
        //{
        //    if (c.Value is IQueryable)
        //    {
        //        Type type = (c.Value as IQueryContext).ElementType;
        //        ObjectContext oc = ObjectContextDictionary.Get(type);

        //        Stack.Push(DataSource.CreateScriptFactory().
        //              Constant(oc.TableName).
        //              Stress().
        //              As(DataSource.CreateScriptFactory().
        //              Constant(FromNameDictionary.Set(type)).
        //              Stress()));

        //        return c;
        //    }
        //    else
        //        return base.VisitConstant(c);

        //}

        #endregion

        #endregion
    }
}
